const { app, BrowserWindow, Menu, MenuItem, ipcMain } = require('electron');
const path = require('path');
const Server = require('../server/index.js');

const isDev = !app.isPackaged;

let mainWindow = null;

Menu.setApplicationMenu(null);

function createWindow () {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 500,
    title: '会员管理系统',
    webPreferences: {
      nodeIntegration: true, //使用node
      contextIsolation: false,
    },
  });

  if (isDev) {
    mainWindow.loadURL('http://localhost:8000');
  } else {
    mainWindow.loadURL(path.resolve(__dirname, '../../dist/index.html'));
  }

  mainWindow.on('closed', () => {
    mainWindow = null;
  });
}

app.on('ready', () => {
  createWindow();
  Server.start();
  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

function openAboutMe() {
  let windowAboutMe = new BrowserWindow({
    width: 1280,
    height: 920,
  });
  windowAboutMe.loadURL('http://youngam.cn');
  windowAboutMe.on('closed', () => {
    windowAboutMe = null;
  });
}

function initMenu() {
  const menu = new Menu();
  menu.append(new MenuItem({ label: '刷新', role: 'reload' }));
  menu.append(new MenuItem({ label: '复制', role: 'copy' }));
  menu.append(new MenuItem({ label: '全选', role: 'selectAll' }));
  menu.append(new MenuItem({ label: '粘贴', role: 'paste' }));
  if (app.isPackaged) {
    menu.append(new MenuItem({ label: '关于作者', click: openAboutMe }));
  } else {
    menu.append(new MenuItem({ label: '开发者工具', role: 'toggleDevTools' }));
  }

  return menu;
}

// 监听右键事件
const contextMenu = initMenu();
ipcMain.on('contextMenu', () => {
  contextMenu.popup();
});
